package com.xuzhiguang.light.gateway.server.http.netty;

import com.xuzhiguang.light.gateway.common.request.GatewayRequest;
import io.netty.handler.codec.http.FullHttpRequest;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author xuzhiguang
 */
public class NettyHttpRequest implements GatewayRequest {

    private final FullHttpRequest fullHttpRequest;

    private final long requestTime;

    private Map<String, Object> headers;

    public NettyHttpRequest(FullHttpRequest fullHttpRequest, long requestTime) {
        this.fullHttpRequest = fullHttpRequest;
        this.requestTime = requestTime;
    }

    @Override
    public long getRequestTime() {
        return requestTime;
    }

    @Override
    public String getMethod() {
        return fullHttpRequest.method().name();
    }

    @Override
    public URI getURI() {
        try {
            return new URI(fullHttpRequest.uri());
        } catch (URISyntaxException e) {
            // TODO do something?
            return null;
        }
    }

    @Override
    public Map<String, Object> getHeaders() {

        if (headers == null) {
            this.headers = new HashMap<>(fullHttpRequest.headers().size());

            Iterator<Map.Entry<CharSequence, CharSequence>> iterator = fullHttpRequest.headers().iteratorCharSequence();
            while (iterator.hasNext()) {
                Map.Entry<CharSequence, CharSequence> entry = iterator.next();
                this.headers.put(String.valueOf(entry.getKey()), entry.getValue());
            }
        }
        return this.headers;
    }

    @Override
    public byte[] getBody() {
        return fullHttpRequest.content().array();
    }

    @Override
    public Object getOriginalRequest() {
        return this.fullHttpRequest;
    }

    @Override
    public boolean needRelease() {
        return true;
    }
}
